<template>
  <div class="settings-page">
    <el-row :gutter="24">
      <!-- 系统状态 -->
      <el-col :span="12">
        <el-card class="page-card">
          <template #header>
            <div class="card-header">
              <span><el-icon><Monitor /></el-icon> 系统状态</span>
              <el-button size="small" @click="checkSystemStatus" :loading="loadingStatus">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>

          <div v-loading="loadingStatus" class="status-content">
            <el-descriptions :column="1" border v-if="systemStatus">
              <el-descriptions-item label="服务状态">
                <el-tag :type="systemStatus.status === 'healthy' ? 'success' : 'danger'">
                  {{ systemStatus.status === 'healthy' ? '正常' : '异常' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="FFmpeg">
                <el-tag :type="systemStatus.dependencies?.ffmpeg_available ? 'success' : 'danger'">
                  {{ systemStatus.dependencies?.ffmpeg_available ? '可用' : '不可用' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="FFprobe">
                <el-tag :type="systemStatus.dependencies?.ffprobe_available ? 'success' : 'danger'">
                  {{ systemStatus.dependencies?.ffprobe_available ? '可用' : '不可用' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="活跃任务">
                {{ systemStatus.services?.active_tasks || 0 }} 个
              </el-descriptions-item>
              <el-descriptions-item label="活跃预览">
                {{ systemStatus.services?.active_previews || 0 }} 个
              </el-descriptions-item>
              <el-descriptions-item label="检查时间">
                {{ formatDate(systemStatus.timestamp) }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </el-col>

      <!-- 资源管理 -->
      <el-col :span="12">
        <el-card class="page-card">
          <template #header>
            <span><el-icon><FolderDelete /></el-icon> 资源管理</span>
          </template>

          <div class="resource-content">
            <el-alert type="info" :closable="false" style="margin-bottom: 20px;">
              <template #title>
                <div>清理说明</div>
              </template>
              <div>
                • 清理超过1小时的预览文件<br>
                • 清理超过24小时的临时文件<br>
                • 清理超过7天的输出文件<br>
                • 清理已完成的内存任务记录
              </div>
            </el-alert>

            <div class="cleanup-actions">
              <el-button type="warning" @click="cleanupResources" :loading="cleaningUp">
                <el-icon><Delete /></el-icon>
                一键清理
              </el-button>

              <el-button @click="showAdvancedCleanup = true">
                <el-icon><Setting /></el-icon>
                高级清理
              </el-button>
            </div>

            <div v-if="cleanupResult" style="margin-top: 20px;">
              <el-alert
                  :type="cleanupResult.success ? 'success' : 'error'"
                  :title="cleanupResult.message"
                  :closable="false"
              >
                <div v-if="cleanupResult.details">
                  <p><strong>清理详情:</strong></p>
                  <ul>
                    <li v-if="cleanupResult.details.previews">
                      预览文件: {{ cleanupResult.details.previews }} 个
                    </li>
                    <li v-if="cleanupResult.details.temp_files">
                      临时文件: {{ cleanupResult.details.temp_files }} 个
                    </li>
                    <li v-if="cleanupResult.details.output_files">
                      输出文件: {{ cleanupResult.details.output_files }} 个
                    </li>
                    <li v-if="cleanupResult.details.completed_tasks">
                      任务记录: {{ cleanupResult.details.completed_tasks }} 个
                    </li>
                  </ul>
                </div>
              </el-alert>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统信息和存储使用情况 -->
    <el-row :gutter="24" style="margin-top: 24px;">
      <el-col :span="12">
        <el-card class="page-card">
          <template #header>
            <span><el-icon><InfoFilled /></el-icon> 系统信息</span>
          </template>

          <div v-loading="loadingInfo" class="info-content">
            <el-descriptions :column="1" border v-if="systemInfo">
              <el-descriptions-item label="系统名称">
                {{ systemInfo.info?.application?.name || '未知' }}
              </el-descriptions-item>
              <el-descriptions-item label="版本号">
                <el-tag>{{ systemInfo.info?.application?.version || '未知' }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="作者">
                {{ systemInfo.info?.application?.author || '未知' }}
              </el-descriptions-item>
              <el-descriptions-item label="描述">
                {{ systemInfo.info?.application?.description || '无描述' }}
              </el-descriptions-item>
            </el-descriptions>

            <el-empty v-if="!loadingInfo && !systemInfo" description="无系统信息" />
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="page-card">
          <template #header>
            <div class="card-header">
              <span><el-icon><Document /></el-icon> 参数预设管理</span>
              <el-button type="primary" @click="showPresetManager = true">
                <el-icon><Setting /></el-icon>
                管理预设
              </el-button>
            </div>
          </template>

          <div class="preset-summary">
            <el-statistic title="预设总数" :value="presetStats.total" />

            <div class="quick-actions" style="margin-top: 20px;">
              <el-button @click="showPresetManager = true">
                <el-icon><View /></el-icon>
                查看所有预设
              </el-button>
              <el-button type="primary" @click="createNewPreset">
                <el-icon><Plus /></el-icon>
                新建预设
              </el-button>
            </div>

            <div class="preset-info" style="margin-top: 20px;">
              <el-alert type="info" :closable="false">
                <template #title>
                  <div>预设功能</div>
                </template>
                <div>
                  • 保存常用的参数配置<br>
                  • 快速应用到新的合成任务<br>
                  • 支持导入导出和批量管理<br>
                  • 提高工作效率
                </div>
              </el-alert>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 预设管理对话框 -->
    <PresetManagerDialog
        v-model="showPresetManager"
        @apply="handlePresetApply"
        @save="handlePresetSave"
    />

    <!-- 高级清理对话框 -->
    <el-dialog v-model="showAdvancedCleanup" title="高级清理选项" width="500px">
      <el-form :model="cleanupOptions" label-width="120px">
        <el-form-item label="清理类型">
          <el-checkbox-group v-model="cleanupOptions.types">
            <el-checkbox value="previews">预览文件</el-checkbox>
            <el-checkbox value="temp">临时文件</el-checkbox>
            <el-checkbox value="output">输出文件</el-checkbox>
            <el-checkbox value="tasks">任务记录</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 添加强制清理选项 -->
        <el-form-item label="强制清理">
          <el-switch
              v-model="cleanupOptions.forceCleanup"
              active-text="清理所有文件"
              inactive-text="按时间清理"
          />
          <div style="margin-top: 8px;">
            <el-alert
                v-if="cleanupOptions.forceCleanup"
                type="warning"
                :closable="false"
                show-icon
            >
              警告：强制清理将删除所有文件，不考虑创建时间！
            </el-alert>
          </div>
        </el-form-item>

        <el-form-item label="预览保留时间" v-if="!cleanupOptions.forceCleanup && cleanupOptions.types.includes('previews')">
          <el-input-number
              v-model="cleanupOptions.previewRetentionHours"
              :min="0"
              :max="720"
              style="width: 200px;"
          />
          <span style="margin-left: 8px;">小时（0表示清理所有）</span>
        </el-form-item>

        <el-form-item label="临时文件保留" v-if="!cleanupOptions.forceCleanup && cleanupOptions.types.includes('temp')">
          <el-input-number
              v-model="cleanupOptions.tempRetentionHours"
              :min="0"
              :max="720"
              style="width: 200px;"
          />
          <span style="margin-left: 8px;">小时（0表示清理所有）</span>
        </el-form-item>

        <el-form-item label="输出保留时间" v-if="!cleanupOptions.forceCleanup && cleanupOptions.types.includes('output')">
          <el-input-number
              v-model="cleanupOptions.outputRetentionDays"
              :min="0"
              :max="365"
              style="width: 200px;"
          />
          <span style="margin-left: 8px;">天（0表示清理所有）</span>
        </el-form-item>

        <el-form-item label="任务保留时间" v-if="!cleanupOptions.forceCleanup && cleanupOptions.types.includes('tasks')">
          <el-input-number
              v-model="cleanupOptions.taskRetentionHours"
              :min="0"
              :max="720"
              style="width: 200px;"
          />
          <span style="margin-left: 8px;">小时（0表示清理所有）</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAdvancedCleanup = false">取消</el-button>
        <el-button type="primary" @click="performAdvancedCleanup" :loading="cleaningUp">
          执行清理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PresetManagerDialog from '@/components/PresetManagerDialog.vue'
import api from '@/api'
import {InfoFilled} from "@element-plus/icons-vue";

// 响应式数据
const loadingStatus = ref(false)
const loadingInfo = ref(false)
const systemStatus = ref(null)
const systemInfo = ref(null)
const cleaningUp = ref(false)
const cleanupResult = ref(null)
const showPresetManager = ref(false)
const showAdvancedCleanup = ref(false)
const presetStats = ref({ total: 0 })

const cleanupOptions = ref({
  types: ['previews', 'temp'],
  forceCleanup: false,
  previewRetentionHours: 1,
  tempRetentionHours: 24,
  outputRetentionDays: 7,
  taskRetentionHours: 24
})

const performAdvancedCleanup = async () => {
  if (cleanupOptions.value.types.length === 0) {
    ElMessage.warning('请选择要清理的类型')
    return
  }

  // 强制清理确认
  if (cleanupOptions.value.forceCleanup) {
    try {
      await ElMessageBox.confirm(
          '确定要强制清理所有选中类型的文件吗？此操作不可恢复！',
          '强制清理警告',
          {
            confirmButtonText: '确定清理',
            cancelButtonText: '取消',
            type: 'warning'
          }
      )
    } catch {
      return
    }
  }

  try {
    cleaningUp.value = true
    cleanupResult.value = null

    const options = {
      type: cleanupOptions.value.types.join(','),
      // 如果强制清理，所有时间设为0
      preview_retention_hours: cleanupOptions.value.forceCleanup ? 0 : cleanupOptions.value.previewRetentionHours,
      temp_retention_hours: cleanupOptions.value.forceCleanup ? 0 : cleanupOptions.value.tempRetentionHours,
      output_retention_days: cleanupOptions.value.forceCleanup ? 0 : cleanupOptions.value.outputRetentionDays,
      task_retention_hours: cleanupOptions.value.forceCleanup ? 0 : cleanupOptions.value.taskRetentionHours
    }

    const result = await api.manualCleanup(options)
    cleanupResult.value = result

    if (result.success) {
      ElMessage.success('高级清理完成')
      showAdvancedCleanup.value = false
    } else {
      ElMessage.error('清理失败')
    }
  } catch (error) {
    console.error('高级清理失败:', error)
    ElMessage.error('清理失败')
  } finally {
    cleaningUp.value = false
  }
}

// 方法
const checkSystemStatus = async () => {
  loadingStatus.value = true
  try {
    systemStatus.value = await api.healthCheck()
  } catch (error) {
    console.error('获取系统状态失败:', error)
    ElMessage.error('获取系统状态失败')
  } finally {
    loadingStatus.value = false
  }
}

const getSystemInfo = async () => {
  loadingInfo.value = true
  try {
    systemInfo.value = await api.getSystemInfo()
  } catch (error) {
    console.error('获取系统信息失败:', error)
    ElMessage.error('获取系统信息失败')
  } finally {
    loadingInfo.value = false
  }
}

const loadPresetStats = async () => {
  try {
    const result = await api.getPresets()
    if (result.success) {
      presetStats.value.total = result.presets?.length || 0
    }
  } catch (error) {
    console.error('获取预设统计失败:', error)
  }
}

const cleanupResources = async () => {
  try {
    await ElMessageBox.confirm(
        '确定要清理系统资源吗？这将删除临时文件和过期数据。',
        '清理确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    cleaningUp.value = true
    cleanupResult.value = null

    const result = await api.manualCleanup()
    cleanupResult.value = result

    if (result.success) {
      ElMessage.success('清理完成')
    } else {
      ElMessage.error('清理失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理失败:', error)
      ElMessage.error('清理失败')
    }
  } finally {
    cleaningUp.value = false
  }
}

const createNewPreset = () => {
  showPresetManager.value = true
  // 可以通过事件或者ref调用预设管理器的新建功能
}

const handlePresetApply = (preset) => {
  ElMessage.success(`预设 "${preset.name}" 已应用`)
}

const handlePresetSave = () => {
  loadPresetStats() // 刷新预设统计
}

const formatDate = (dateStr) => {
  if (!dateStr) return '未知'
  try {
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN')
  } catch {
    return '无效日期'
  }
}

// 生命周期
onMounted(() => {
  checkSystemStatus()
  getSystemInfo()
  loadPresetStats()
})
</script>

<style lang="scss" scoped>
.settings-page {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.page-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;

  ::v-deep(.el-card__header) {
    padding: 20px 24px;
    border-bottom: 1px solid #f0f2f5;
  }

  ::v-deep(.el-card__body) {
    padding: 24px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }
}

.status-content,
.resource-content,
.info-content {
  min-height: 200px;
}

.system-info {
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;

  h4 {
    margin: 0 0 16px 0;
    color: #303133;
    font-weight: 600;
  }

  .resource-item {
    text-align: center;

    .resource-label {
      display: block;
      margin-bottom: 8px;
      color: #606266;
      font-size: 14px;
    }
  }
}

.cleanup-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.preset-summary {
  text-align: center;

  .quick-actions {
    display: flex;
    gap: 12px;
    justify-content: center;
    flex-wrap: wrap;
  }
}

.path-text {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #606266;
  word-break: break-all;
}

.el-descriptions {
  ::v-deep(.el-descriptions__label) {
    font-weight: 600;
    color: #303133;
  }

  ::v-deep(.el-descriptions__content) {
    color: #606266;
  }
}

.el-progress {
  ::v-deep(.el-progress__text) {
    font-size: 12px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .settings-page {
    padding: 16px;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    span {
      justify-content: center;
    }
  }

  .cleanup-actions,
  .quick-actions {
    flex-direction: column;
  }

  .system-info {
    .el-row {
      .el-col {
        margin-bottom: 16px;
      }
    }
  }
}
</style>